package org.example.myleet.rosalind.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FastaReader {

    public static List<FastaSequence> parseFastaInput(String input) {
        String[] lines = input.split("\n");
        List<FastaSequence> sequences = new ArrayList<>(lines.length / 2);
        StringBuilder sequence = new StringBuilder();
        String tag = null;
        for (String line : lines) {
            if (line.startsWith(">")) {
                String t = line.substring(1);
                if (sequence.length() > 0) {
                    FastaSequence seq = new FastaSequence(tag, sequence.toString());
                    sequences.add(seq);
                    sequence.delete(0, sequence.length());
                }
                tag = t;
            } else {
                sequence.append(line);
            }
        }
        if (sequence.length() > 0) {
            FastaSequence seq = new FastaSequence(tag, sequence.toString());
            sequences.add(seq);
        }
        return sequences;
    }

    public static List<FastaSequence> parseFastaFromFile(String filePath) {
        StringBuilder sequence = new StringBuilder();
        String tag = null;
        BufferedReader reader;
        List<FastaSequence> sequences = new ArrayList<>();
        try {
            reader = new BufferedReader(new FileReader(filePath));
            String line;
            while (null != (line = reader.readLine()) && line.length() > 0) {
                if (line.startsWith(">")) {
                    String t = line.substring(1);
                    if (sequence.length() > 0) {
                        FastaSequence seq = new FastaSequence(tag, sequence.toString());
                        sequences.add(seq);
                        sequence.delete(0, sequence.length());
                    }
                    tag = t;
                } else {
                    sequence.append(line);
                }
            }
            if (sequence.length() > 0) {
                FastaSequence seq = new FastaSequence(tag, sequence.toString());
                sequences.add(seq);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sequences;
    }
}
